//index.js
//获取应用实例
var count_down = require('../../utils/countDown.js');
var commonapi = require('../../component/service/commonapi.js');
var pintuanapi = require('../../component/service/pintuanapi.js');
var skuapi = require('../../component/service/skuapi.js');
var countDownT = require('../../component/countDown/countDownT.js');
var keywordapi = require('../../component/service/keywordapi.js');
Page({
  data: {
    host: getApp().globalData.host,
    recommends: [],
    skus: [],
    biddings: [],
    listings: [],
    skuName: '',
    advs: [],
    puersheng: [],
    puershu: [],
    countDown: {},
    wholesaleImg:{},
    puershengImg:{},
    puershuImg:{},
    pintuans:[],
    pintuanImg:{},
    materials:[],
    materialImg:{},
    activities:[],
    searchHistory:[],
    searchMode:false //是否为搜索模式
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    this.getRecommends();
    //this.getBiddings();
    //this.getListings();
    this.getadvs();
    this.wxScan(options.q);
    let that = this;
    commonapi.getAdvs(8,function(res){
      that.setData({
        wholesaleImg:res[0]
      })
    });
    commonapi.getAdvs(9,function(res){
      that.setData({
        puershengImg: res[0]
      })
    });
    commonapi.getAdvs(10,function(res){
      that.setData({
        puershuImg:res[0]
      })
    });
    //拼团列表
    pintuanapi.inProcessList(0,4,function(res){
      for (let i = 0; i < res.length; i++) {
        let countDown = new countDownT();        
        countDown.setExpireTime(res[i].serverTime,res[i].expireTime,"pintuans[" + i + "].countDownT",that);
        res[i].countDownT = countDown;
        res[i].percent = parseInt(res[i].actualQuantity*100/res[i].planQuantity);
      }
      that.setData({
        pintuans:res
      })
    });
    //拼团广告图
    commonapi.getAdvs(11,function(res){
      that.setData({
        pintuanImg:res[0]
      })
    });
    //查询毛料信息
    skuapi.materialList(0,4,function(res){
      that.setData({
        materials:res
      })
    });
    //毛料广告图
    commonapi.getAdvs(12,function(res){
      that.setData({
        materialImg:res[0]
      })
    });
    //首页活动内容
    commonapi.getAdvs(13,function(res){
      that.setData({
        activities:res
      })
    });
  },
  getRecommends: function () {
    var that = this;
    wx.request({
      url: that.data.host + 'skuRecommendListForIndex',
      header: getApp().globalData.header,
      data:{'pageSize':6},
      method:'POST',
      success: function (res) {
        if(typeof(res.data)!='undefined'){
          that.dealPromotion(res.data,function(res){
            that.setData({
              recommends: res
            })
          });      
        }
      },
      fail: function (res) { },
      complete: function (res) {
        that.getSkus();  //recommends和skus不能同时加载，不然response报错
      }
    })
  },
  dealPromotion:function(data,callback){
    if(typeof(data)!='undefined'){
      for(let i = 0;i<data.length;i++){
        if(typeof(data[i].imgUrl)!='undefined'&&data[i].imgUrl.indexOf('img/')<2){ //处理图片兼容性
          data[i].imgUrl = getApp().globalData.imgHost + data[i].imgUrl;
        }
        if(typeof(data[i].summary)!='undefined'&&data[i].summary.indexOf('买一送一')>-1){
          data[i].promotion = true;
        }
      }
    }
    callback(data);
  },
  getBiddingDetail: function (event) {
    var biddingId = event.currentTarget.dataset.biddingId;
    wx.navigateTo({
      url: '../bidding/bidding?biddingId=' + biddingId,
    })
  },
  getListingDetail: function (event) {
    var listingId = event.currentTarget.dataset.listingId;
    wx.navigateTo({
      url: '../listing/listing?listingId=' + listingId,
    })
  },
  getSkus: function () {
    var that = this;
    wx.request({
      //url: that.data.host + '/webapp/resource/getSkus.html',
      //data: {pageSize: 6, pageNo: 1},
      url: that.data.host + 'sku/list',
      data: { pageSize: 20, pageIndex: 0 },
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        if (res.data.records != '' && res.data.records != null && typeof (res.data.records) != 'undefined' && res.data.records.length != 0) {
          that.dealPromotion(res.data.records,function(res){
            that.setData({
              skus: res
            })
          });
        }
      },
      fail: function (res) { },
      complete: function (res) {
        that.getPuerSheng();
      }
    })
  },
  getPuerSheng: function () {
    var that = this;
    wx.request({
      url:that.data.host + 'sku/list',
      data: {pageSize: 6, pageIndex: 0,typeName:'普洱',craftName:'生茶'},
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        if (res.data.records != '' && res.data.records != null && typeof(res.data.records)!='undefined' && res.data.records.length!=0) {
          that.dealPromotion(res.data.records,function(res){
            that.setData({
              puersheng: res
            })
          });
        }
      },
      fail: function (res) { },
      complete: function (res) {
        that.getPuerShu();
      }
    })
  },
  getPuerShu: function () {
    var that = this;
    wx.request({
      url:that.data.host + 'sku/list',
      data: {pageSize: 6, pageIndex: 0,typeName:'普洱',craftName:'熟茶'},
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        if (res.data.records != '' && res.data.records != null && typeof(res.data.records)!='undefined' && res.data.records.length!=0) {
          that.dealPromotion(res.data.records,function(res){
            that.setData({
              puershu: res
            })
          });
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  getSkuDetail: function (event) {
    var skuId = event.currentTarget.dataset.skuId;
    wx.navigateTo({
      url: '../sku/sku?skuId=' + skuId,
    })
  },
  //拼团详情页
  getPintuanDetail:function(e){
    var itemId = e.currentTarget.dataset.itemId;
    wx.navigateTo({
      url: '../pintuan/pintuan?itemId=' + itemId,
    })
  },

  getBiddings: function () {
    var that = this;
    wx.request({
      url: that.data.host + 'webapp/business/getBiddings.html',
      header: getApp().globalData.header,
      data: { statusStr: 2, pageSize: 3, pageNo: 1 },
      success: function (res) {
        if (res.data.results.length > 0) {
          var resData = res.data.results;
          for (var i = 0; i < resData.length; i++) {
            count_down.countDown('', resData[i].expireTime, that, resData[i].biddingCode);
          }
          that.setData({
            biddings: resData
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  getListings: function () {
    var that = this;
    wx.request({
      url: that.data.host + 'webapp/listing/all.html',
      header: getApp().globalData.header,
      data: { pageSize: 3, pageNo: 1 },
      success: function (res) {
        if (res.data.results.length > 0) {
          var resData = res.data.results;
          for (var i = 0; i < resData.length; i++) {
            count_down.countDown('', resData[i].expireTime, that, resData[i].listingCode);
          }
          that.setData({
            listings: resData
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  getadvs: function () {
    var that = this;
    wx.request({
      url: that.data.host + 'webapp/main/advlist.html',
      header: getApp().globalData.header,
      success: function (res) {
        if (res.data.length > 0) {
          that.setData({
            advs: res.data
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  //搜索
  inputSearch: function (e) {
    this.setData({
      skuName: e.detail.value
    })
  },
  searchSkus: function () {
    var skuName = this.data.skuName;
    this.setData({
      searchMode:false
    })
    wx.navigateTo({
      url: '../skus/skus?skuName=' + skuName,
    })
  },
  //跳转至搜索页
  forwardSearch:function(){
    let that = this;
    that.setData({
      searchHistory:[]
    })
    keywordapi.history(function(res){
      that.setData({
        searchHistory:res
      })
    });
    that.setData({
      searchMode:true
    })
  },
  //选择关键词
  selectKeyword:function(e){
    this.setData({
      skuName:e.currentTarget.dataset.skuName
    })
    this.searchSkus();
  },
  cancelSearch:function(){
     this.setData({
      skuName:'',
      searchMode:false
    })
  },
  //删除搜索历史记录
  removeHistory:function(){
    if(this.data.searchHistory.length>0){
      let that = this;
      wx.showModal({
        title:'删除搜索历史',
        content:'确认删除所有历史搜索记录吗？',
        success: function(res) {
          if(res.confirm) {
            keywordapi.removeAll();
            that.setData({
              searchHistory:[]
            })
          }
        }
      })
    }    
  },
  jumpToSkus: function (e) {
    var skuName = e.currentTarget.dataset.skuName;;
    wx.navigateTo({
      url: '../skus/skus?skuName=' + skuName,
    })
  },
  bindconfirm: function (e) {
    var skuName = this.data.skuName;
    wx.navigateTo({
      url: '../skus/skus?skuName=' + skuName,
    })
  },
  //点击banner广告跳转
  clickAdvs:function(e){
    let link = e.target.dataset.link;
    this.wxScan(link);
  },
  scanCode: function () {
    var that = this;
    wx.scanCode({
      success: function (res) {
        if ("scanCode:ok" == res.errMsg) {//扫描成功
          that.wxScan(res.result);
          /** 
          wx.request({
            url: that.data.host + 'webapp/control/scan.html',
            data:{url:res.result},
            header: getApp().globalData.header,
            success: function (res) {
              if(res.data.length>0){
                wx.navigateTo({
                  url: res.data,
                })
              }
            },
            fail: function (res) { },
            complete: function (res) { }
          })
          **/
        }
      }
    })
  },
  //用户通过微信扫一扫进入页面 ,通过服务器controller处理，将来可扩展性更强
  wxScan: function (url) {
    if (typeof (url) == 'undefined' || url.length < 1)
      return;
    url = unescape(url);
    console.log('wxscan url -->' + url);
    //注册页面根据情况跳转
    if (url.indexOf('register.html') > 0) {
      setTimeout(function () {//app.js登录为异步登录，此处等待2s
        if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
          wx.navigateTo({
            url: '../login/login'
          });
        } else
          return;
      }, 2000);
    }
    //用户通过网页版扫码进入
    if(url.indexOf('login.html') > 0){
      wx.showLoading({
        title: '处理中...',
      })
      setTimeout(function () {//app.js登录为异步登录，此处等待2s
        wx.hideLoading();
        if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
          wx.navigateTo({
            url: '../login/login' + url.substr(url.indexOf('login.html') + 10)
          });
        } else if(url.indexOf("tokenKey")>0){ 
          //此处弹窗让用户确认登录网页版
          wx.showModal({
          title: '扫码登录',
          content: '云茶国际网页端登录确认',
          success: function(res) {
            if (res.confirm) {//用户确认登录
              commonapi.scanLogin(url.substr(url.indexOf('tokenKey') + 9));
            }
          }
        })
          return;
        }else
          return;
      }, 2000);
    }
    var that = this;
    wx.request({
      url: that.data.host + 'webapp/control/wxScan.html',
      data: { url: url },
      header: getApp().globalData.header,
      success: function (res) {
        if (typeof (res.data) != 'undefined' && res.data.length > 1) {
          wx.navigateTo({
            url: res.data,
          })
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  //分享该页面
  onShareAppMessage: function () {
    return {
      title: '[分享]一起喝茶吧！',
      path: '/pages/index/index'
    }
  },
  skulist: function () {
    wx.navigateTo({
      url: '../skus/skus'
    });
  },
  binddinglist: function () {
    wx.navigateTo({
      url: '../biddings/biddings'
    });
  },
  listinglis: function () {
    wx.navigateTo({
      url: '../listings/listings'
    });
  }
})
